package jwt

import (
	"RocFamilySystem/config"
	"RocFamilySystem/pkg/constant"
	"github.com/golang-jwt/jwt/v5"
	"log"
	"time"
)

// GeneratorToken 生成Token
func GeneratorToken(sub string) string {
	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"iss": "dpengchen@163.com",
		"sub": sub,
		"iat": float64(time.Now().UnixMilli()),
	}).SignedString([]byte(config.GlobalConfig.JWT.SecurityKey))

	if err != nil {
		log.Println("生成Token失败！")
		panic(err)
	}
	return token
}

// ParseToken 解析Token
func ParseToken(token string) string {
	parse, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.GlobalConfig.JWT.SecurityKey), nil
	})
	if err != nil {
		log.Println("解析Token失败！")
		log.Panicln(constant.AUTHORITY_ERROR)
	}

	subject, err := parse.Claims.GetSubject()
	if err != nil {
		log.Println("解析Token失败，不存在sub！")
		log.Panicln(constant.AUTHORITY_ERROR)
	}
	return subject
}
